package com.zy.qudadid.ui.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.pingplusplus.android.Pingpp;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;
import com.zy.app.CarAppConts;
import com.zy.bean.Dingdan;
import com.zy.lcpassenger.R;
import com.zy.qudadid.network.Const;
import com.zy.qudadid.presenter.base.BasePresenterImp;
import com.zy.qudadid.ui.activity.base.ToolBarActivity;
import com.zy.qudadid.utils.AESCrypt;
import com.zy.util.JsonUtils;
import com.zy.util.Util;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;

import okhttp3.Call;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;

/**
 * Created by Administrator on 2016/7/21 0021.
 */
public class PayActivity extends ToolBarActivity {

    ImageView back;
    Dingdan dingdan;
    Button z_zhifu;
    TextView z_money;
    CheckBox z_weixin,z_xianjin,z_zhifubao;
    RelativeLayout rlCash;
    private int num = -1;
    private String cid = "0";
    TextView z_xiaofei;
    LinearLayout ll_tip;

    private String price="";

    @Override
    protected int provideContentViewId() {
        return R.layout.activity_zhifuyemian;
    }

    @Override
    public void initListeners() {

    }

    @Override
    public BasePresenterImp createPresenter() {
        return null;
    }

    @Override
    protected void initThings(Bundle savedInstanceState) {
        super.initThings(savedInstanceState);
        dingdan = (Dingdan) getIntent().getBundleExtra("data").getSerializable("dingdan");

        back = (ImageView) findViewById(R.id.back);
        rlCash = (RelativeLayout) findViewById(R.id.rlCash);
        if(dingdan.info.state.equals("8")){ //
            rlCash.setVisibility(View.GONE);
        }else{
            rlCash.setVisibility(View.VISIBLE);
        }


        z_money = (TextView)findViewById(R.id.z_money);
        z_xiaofei = (TextView)findViewById(R.id.z_xiaofei);
        z_weixin = (CheckBox)findViewById(R.id.z_weixin);
        z_xianjin = (CheckBox)findViewById(R.id.z_xianjin);
        z_zhifubao = (CheckBox)findViewById(R.id.z_zhifubao);
        z_zhifu = (Button)findViewById(R.id.z_zhifu);
        ll_tip = (LinearLayout) findViewById(R.id.ll_tip);
        z_money.setText(dingdan.info.price);

        price = dingdan.info.price;

        if(Double.parseDouble(dingdan.info.tip)>0) {
            ll_tip.setVisibility(View.VISIBLE);
            z_xiaofei.setText(dingdan.info.tip);

            price = (Double.parseDouble(dingdan.info.price)+Double.parseDouble(dingdan.info.tip))+"";
        }else{
            ll_tip.setVisibility(View.GONE);
        }


        z_weixin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                num = 0;
                channel = "wx";
                z_xianjin.setChecked(false);
                z_zhifubao.setChecked(false);
            }
        });

        z_xianjin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                num = 1;
                z_weixin.setChecked(false);
                z_zhifubao.setChecked(false);
            }
        });


        z_zhifubao.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                num = 3;
                channel = "alipay";
                z_xianjin.setChecked(false);
                z_weixin.setChecked(false);
            }
        });

        z_zhifu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (num){
                    case 0:
                        pay();
                        break;
                    case 1:
                        offPay();
                        break;
                    case 3:
                        pay();
                        break;
                }
            }
        });
    }

    public void startActivityForResult(Class clazz, int requestCode) {
        startActivityForResult(new Intent(getBaseContext(), clazz), requestCode);
    }


    private String channel="";

    public void pay(){
        try {
            HashMap<String, String> map = new HashMap<>();
            AESCrypt aesCrypt = new AESCrypt();
            map.put("channel", channel);
            map.put("amount", price);
            map.put("ordernum", dingdan.info.oid);
            map.put("subject", "先锋的订单");
            map.put("body", "先锋打车消费");
            String json = JsonUtils.toJson(map);
            String d = Util.replaceBlank(aesCrypt.encrypt(json));

            OkHttpUtils.post()
                    .url(Const.BASE_URL+"api.php/pay/pay")
                    .addParams("args", d)
                    .build()
                    .execute(new StringCallback() {
                        @Override
                        public void onError(Call call, Exception e, int i) {
                            Toast.makeText(getBaseContext(), "订单创建失败", Toast.LENGTH_LONG).show();
                        }

                        @Override
                        public void onResponse(String response,int i) {
                            try {
                                JSONObject jsonObject = new JSONObject(response);
                                Pingpp.createPayment(PayActivity.this, response);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    });


            String url = Const.BASE_URL+"api.php/pay/pay";
            OkHttpClient client = new OkHttpClient();
         //   Request request = new Request.Builder().url(url).addParams("args", d).build();
            FormBody body = new FormBody.Builder()
                    .add("args",d)
                    .build();
            //创建请求对象
            Request request = new Request.Builder()
                    .post(body)
                    .url(url)
                    .build();
            okhttp3.Response response = client.newCall(request).execute();
            if (response.isSuccessful()) {
                Log.i("-----", response.body().string());
            } else {
                Log.i("-----", "okHttp is request error");
            }

            //返回的时候在子线程，需要handler更新UI
//            runOnUiThread(new Runnable() {
//                @Override
//                public void run() {
//                    mTextView.setText(content);
//                }
//            });

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //支付页面返回处理
        if (requestCode == Pingpp.REQUEST_CODE_PAYMENT) {
            if (resultCode == Activity.RESULT_OK) {
                String result = data.getExtras().getString("pay_result");

                // 处理返回值
                // "success" - 支付成功
                // "fail"    - 支付失败
                // "cancel"  - 取消支付
                // "invalid" - 支付插件未安装（一般是微信客户端未安装的情况）
                switch (result){
                    case "success":
                        Toast.makeText(getApplicationContext(), "支付成功", Toast.LENGTH_SHORT).show();
                        finish();
                        break;
                    case "fail":
                        Toast.makeText(getApplicationContext(), "支付失败", Toast.LENGTH_SHORT).show();
                        break;
                    case "cancel":
                        Toast.makeText(getApplicationContext(), "取消支付", Toast.LENGTH_SHORT).show();
                        break;
                    case "invalid":
                        Toast.makeText(getApplicationContext(), "支付插件未安装", Toast.LENGTH_SHORT).show();
                        break;
                }

                String errorMsg = data.getExtras().getString("error_msg"); // 错误信息
                String extraMsg = data.getExtras().getString("extra_msg"); // 错误信息
                String test = "";
//                showMsg(result, errorMsg, extraMsg);
            }
        }

        if (requestCode == 1021 && resultCode == 2010) {
            cid = data.getStringExtra("cid");
//            youhuiquan.setText(data.getStringExtra("msg"));

        }
    }

    public void offPay(){
        //获取用户钱包余额
        try {
            HashMap<String, String> map = new HashMap<>();
            AESCrypt aesCrypt = new AESCrypt();
            map.put("amount", dingdan.info.price);
            map.put("ordernum", dingdan.info.oid);
            map.put("channel", "cash");
            String json = JsonUtils.toJson(map);
            String d = Util.replaceBlank(aesCrypt.encrypt(json));
            OkHttpUtils.post()
                    .url(CarAppConts.base_url + "api.php/order/cash")
                    .addParams("args", Util.replaceBlank(aesCrypt.encrypt(json)))
                    .build()
                    .execute(new StringCallback() {
                        @Override
                        public void onError(Call call,Exception e,int i) {
                            Toast.makeText(getBaseContext(), "线下支付失败", Toast.LENGTH_LONG).show();
                        }

                        @Override
                        public void onResponse(String response,int i) {
                            try {
                                JSONObject jsonObject = new JSONObject(response);
                                if (jsonObject.getString("code").equals("200")) {
                                    Toast.makeText(getApplicationContext(), "现金支付成功，等待司机确认", Toast.LENGTH_SHORT).show();
                                    finish();
                                }else{
                                    Toast.makeText(getApplicationContext(), jsonObject.getString("message"), Toast.LENGTH_SHORT).show();
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    });
            Log.i("GGGG","denglu加密==="+ Util.replaceBlank(aesCrypt.encrypt(json))+"     lainjie==="+CarAppConts.base_url+"login_with_reg&args="+Util.replaceBlank(aesCrypt.encrypt(json)));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected CharSequence provideTitle() {
        return "支付";
    }
}
